package com.yupi.yupicturebackend.manager;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.RandomUtil;
import com.qcloud.cos.model.PutObjectResult;
import com.qcloud.cos.model.ciModel.persistence.ImageInfo;
import com.yupi.yupicturebackend.Exception.BusinessException;
import com.yupi.yupicturebackend.Exception.ErrorCode;
import com.yupi.yupicturebackend.Exception.ThrowUtils;
import com.yupi.yupicturebackend.config.CosClientConfig;
import com.yupi.yupicturebackend.model.dto.UploadPictureResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;
import javax.annotation.Resource;
import java.io.File;
import java.util.Arrays;
import java.util.List;

/**
 * 已废弃，已封装为模板类
 */
@Component
@Slf4j
@Deprecated
public class FileManager {

    @Resource
    private CosClientConfig cosClientConfig;
    @Resource
    private CosManager cosManager;
    /**
     * 通用图片上传
     */
    public UploadPictureResult uploadPictureResult(MultipartFile multipartFile, String prefix) {
        //  1.校验文件合法性
        isValid(multipartFile);
        // 2. 拼接文件上传url
        String UUID = RandomUtil.randomString(8);
        String filename = multipartFile.getOriginalFilename();

        String upload_Name = String.format("%s_%s.%S", DateUtil.now(), UUID, FileUtil.getSuffix(filename));
        String upload_Path = String.format("%s/%s", prefix, upload_Name);
        // 3.解析文件属性，封装对象返回给调用者

        File file = null;
        try {
            // 创建临时文件
            file = File.createTempFile(upload_Path, null);
            // 填充临时文件
            multipartFile.transferTo(file);
            // 将临时文件上传到cos
            PutObjectResult putObjectResult = cosManager.putPictureObject(upload_Path, file);
            // 获取图片对象
            ImageInfo imageInfo = putObjectResult.getCiUploadResult().getOriginalInfo().getImageInfo();
            String format = imageInfo.getFormat();
            int width = imageInfo.getWidth();
            int height = imageInfo.getHeight();
            double scale = NumberUtil.round(height * 1.0 / width, 2).doubleValue();

            // 封装返回结果
            UploadPictureResult uploadPictureResult = new UploadPictureResult();
            uploadPictureResult.setUrl(cosClientConfig.getHost() + '/' + upload_Path);
            uploadPictureResult.setPicName(upload_Name);
            uploadPictureResult.setPicSize(FileUtil.size(file));
            uploadPictureResult.setPicWidth(width);
            uploadPictureResult.setPicHeight(height);
            uploadPictureResult.setPicScale(scale);
            uploadPictureResult.setPicFormat(format);

            // 返回文件对象
            return uploadPictureResult;
        } catch (Exception e) {
            log.error("图片上传到存储对象失败！path={}, name={}", upload_Path, upload_Name, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传文件失败");
        } finally {
            // 删除临时文件
            deleteTemplateFile(file);
        }
    }

    public void deleteTemplateFile(File file) {
        if (file != null) {
            boolean success = file.delete();
            if (!success) {
                // 没有删除成功
                log.error("delete temp file fail,filepath = {}", file.getAbsolutePath());
            }
        }
    }

    private void isValid(MultipartFile multipartFile) {
        // 1.文件不能为空
        ThrowUtils.throwIf(multipartFile == null, ErrorCode.PARAMS_ERROR, "文件不能为空！");
        // 2. 文件大小不能超过3M
        long ONE_MB = 1024 * 1024;
        // 2.1获取文件大小
        long fileSize = multipartFile.getSize();
        ThrowUtils.throwIf(fileSize > 3 * ONE_MB, ErrorCode.PARAMS_ERROR, "文件大小不能超过3M！");

        // 3. 文件类型校验，校验后缀
        List<String> suffixList = Arrays.asList("jpg", "jpeg", "png", "gif", "bmp", "webp");
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        ThrowUtils.throwIf(!suffixList.contains(fileSuffix), ErrorCode.PARAMS_ERROR, "文件类型错误！");
    }

}



